﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using GrupyzServices.Logging;
using System.Web;
using Webdiyer.WebControls.Mvc;

namespace GrupyzServices.BdAccess
{
    public class ComentarioRepository : IComentarioRepository
    {
        GrupyzEntities _entity;
        ILogger log;

        public ComentarioRepository()
        {
            log = new NLogLogger();
            _entity = new GrupyzEntities();
        }   

        public PagedList<ComentarioViewModel> GetComentariosDeal(int idDeal,int? pag)
        {
            var result = from x in _entity.Comentario.Include("Cliente")
                         where x.DealId == idDeal
                         orderby x.Data descending
                         select new ComentarioViewModel {
                         Data = x.Data,
                         IdDeal = idDeal,
                         Imagem = x.Cliente.UriImagem,
                         NomeCliente = x.Cliente.Nome,
                         Texto = x.Texto
                         };

             return result.ToPagedList(pag ?? 1, 10);
        }

        public IEnumerable<Comentario> GetUltimosComentários()
        {
            throw new NotImplementedException();
        }

        public bool CreateComentario(dynamic comentario)
        {
            try
            {
                Comentario com = new Comentario();
                com.ClienteId = int.Parse(comentario["ClienteId"]);
                com.Data = DateTime.Now;
                com.DealId = int.Parse(comentario["DealId"]);
                com.Texto = comentario["Texto"]; 

                _entity.Comentario.AddObject(com);
                _entity.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return false;
            }
        }


        public Comentario GetUltimoComentarioDeal(int idDeal)
        {
            return (from x in _entity.Comentario.Include("Cliente")
                   where x.DealId == idDeal
                   orderby x.Data descending
                   select x).FirstOrDefault();
        }

        public int GetComentarioDealCount(int idDeal)
        {
            return (from x in _entity.Comentario
                   where x.DealId == idDeal
                   select x).Count();
        }
    }
}
